from odoo import fields, models, api
from odoo.exceptions import UserError
from odoo.addons.rp_customer_management.models.inherit.res_partner_inherit_for_customer import ADDRESS_TYPE

BOOK_PICK_STATE = [('initiated', '已发起'), ('booked', '已预约'), ('completed', '已完成'), ('book_failure', '预约失败'), ('pickup_failure', '取件失败'), ('cancel', '已取消')]
BOOK_PICK_TYPE = [('shipment', '运单发起'), ('individual', '单独预约')]


class RPBookPickup(models.Model):
    _name = 'rp.book.pickup'
    _description = '预约上门取件'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _rec_name = 'code'
    _order = 'create_date DESC'

    def _default_get_kg(self):
        kg = self.env['uom.uom'].search([('name', '=', 'kg')])
        return kg.id if kg else False

    def _default_get_cm3(self):
        cm = self.env['uom.uom'].search([('name', '=', 'cm³')])
        return cm.id if cm else False

    code = fields.Char(string='预约单号', default='RP_BP/20230101/*****', readonly=True, index=True, copy=False)
    state = fields.Selection(string='状态', selection=BOOK_PICK_STATE, default=BOOK_PICK_STATE[0][0], copy=False, tracking=True)
    type = fields.Selection(string='类型', selection=BOOK_PICK_TYPE, default=BOOK_PICK_TYPE[1][0], copy=False, tracking=True)
    shipment_id = fields.Many2one(string='运单', comodel_name='rp.shipment', tracking=True)
    customer_id = fields.Many2one(string='客户', comodel_name='rp.customer', tracking=True)

    book_d = fields.Date(string='预约时间', default=fields.Date.today(), tracking=True)
    book_t = fields.Many2one(string='预约时段', comodel_name='rp.book.time', tracking=True)
    book_note = fields.Text(string='预约说明', tracking=True)

    shipper_id = fields.Many2one(string='托运商', comodel_name='rp.shipper')
    shipper_mail_route_id = fields.Many2one(string='托运商服务', comodel_name='rp.shipper.mail.route')

    # 发件人信息
    send_country_id = fields.Many2one(string='发件国家', comodel_name='res.country', tracking=True)
    send_postal_code_id = fields.Many2one(string='发件邮编', comodel_name='rp.postal.code', tracking=True)
    send_state_id = fields.Many2one(string='发件省', comodel_name='res.country.state', compute='_depends_send_postal_code_id', store=True)
    send_city_id = fields.Many2one(string='发件市', comodel_name='res.city', compute='_depends_send_postal_code_id', store=True)
    send_street = fields.Char(string='发件街道', tracking=True)
    send_first_name = fields.Char(string='发件人名', tracking=True)
    send_last_name = fields.Char(string='发件人姓', tracking=True)
    send_phone = fields.Char(string='发件电话', tracking=True)
    send_address_type = fields.Selection(string='发件地址类型', selection=ADDRESS_TYPE, default=ADDRESS_TYPE[0][0], tracking=True)
    send_company_name = fields.Char(string='发件公司名称', tracking=True)

    rp_parcel_ids = fields.Many2many(string='包裹明细', comodel_name='rp.parcel',
                                     relation='rp_book_pickup_and_parcel_rel', column1='shipment_id', column2='parcel_id')

    parcel_total_weight = fields.Float(string='包裹总重', digits=(8, 3), default=0, )
    parcel_actual_weight = fields.Float(string='包裹实际重量', digits=(8, 3), default=0, )
    parcel_rounded_weight = fields.Float(string='包裹取整重量', digits=(8, 3), default=0, )
    weight_uom_id = fields.Many2one(string='重量单位', comodel_name='uom.uom', default=_default_get_kg)
    parcel_total_volume = fields.Float(string='包裹总体积', digits=(8, 3), default=0, )
    volume_uom_id = fields.Many2one(string='体积单位', comodel_name='uom.uom', default=_default_get_cm3)

    remarks = fields.Char(string='备注')
    active_flag = fields.Boolean(string='有效', default=True)

    @api.depends('send_postal_code_id')
    def _depends_send_postal_code_id(self):
        """ 填入发件邮编自动填充发件省、市 """
        for s in self:
            if s.send_postal_code_id:
                s.write({'send_state_id': s.send_postal_code_id.state_id.id,
                         'send_city_id': s.send_postal_code_id.city_id.id})

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['code'] = self.env['ir.sequence'].sudo().next_by_code('rp.book.pickup') or '/'
        return super(RPBookPickup, self).create(vals_list)

    @api.onchange('type')
    def _onchange_type(self):
        """ 暂不支持单独预约 """
        if self.type == BOOK_PICK_TYPE[1][0]:
            raise UserError('暂不支持单独预约')

    def confirm_book(self):
        """ 确认预约 """
        if self.state in [BOOK_PICK_STATE[0][0], BOOK_PICK_STATE[3][0]]:
            self.write({'state': 'booked'})

    def cancel_book(self):
        """ 取消预约 """
        if self.state in [BOOK_PICK_STATE[0][0], BOOK_PICK_STATE[1][0]]:
            self.write({'state': BOOK_PICK_STATE[5][0],
                        'active_flag': False})
            self.shipment_id.write({'book_pickup_id': False})
